package com.unsiv.torch;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
/**
 * <p>screen torch</p>
 * @author fanzhen
 * @time   10:43:45 PM Sep 8, 2011
 * @email  fanzhen.meng@gmail.com
 */
public class ScreenTorch extends Activity {
	private static final String TAG = "ScreenTorch";
	private static final int MODE_BRIGHTNESS = 0;
	private static final int MODE_STROBE = 1;
	private static final int MODE_CUSTOMIZE = 2;
	private int mCurrentMode = -1;

	private ImageView ibutton_information;
	private ImageView ibutton_program;
	private ImageView ibutton_help;
	private RelativeLayout mylayout;
	private Resources myColor;
	private SharedPreferences setting;
	private SharedPreferences screen_mode;
	private Editor settingEditor;
	private int mFlag;
	private FlashHandler flashHandler;
	private PowerManager.WakeLock mWakeLock;
	private int customizeDelayIndex;
	private String[] customizeDelayValues;
	private CustomizeHandler customizeHandler;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.screen);
		mylayout = (RelativeLayout)findViewById(R.id.screen_layout);
		setColor(R.color.white);
		setting = getSharedPreferences("setting", 0);
		settingEditor = setting.edit();
		screen_mode = getSharedPreferences("screen_mode", 0);
		selectMode(0);
		ibutton_information = (ImageView) findViewById(R.id.screen_information);
		ibutton_program = (ImageView) findViewById(R.id.screen_program);
		ibutton_help = (ImageView) findViewById(R.id.screen_help);
		mylayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				selectMode(1);
			}
		});
		ibutton_information.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplication(), Information.class);
				startActivity(intent);
			}
		});
		ibutton_program.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplication(), Program.class);
				intent.putExtra("type", "screen");
				startActivity(intent);
			}
		});
		ibutton_help.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplication(), Help.class);
				startActivity(intent);
			}
		});
		mWakeLock = getWakeLock();
		if(mWakeLock !=null)
			mWakeLock.acquire();
	}
	@Override
	protected void onStop() {
		if(mWakeLock !=null)
		{
			mWakeLock.release();	
			mWakeLock = null;
		}
		super.onStop();
	}
	private void selectMode(int flag){
		int currentModeId = setting.getInt("current_screen_mode", 1);
		int nextModeId = currentModeId;
		if(flag==1){
			nextModeId = calculateMode(currentModeId);
		}
		String nextMode = screen_mode.getString(String.valueOf(nextModeId), "1");
		String[] nextModeValues  = nextMode.split(",");
		if(nextModeValues[0].equals("brightness")){
			//set screen brightness
			mCurrentMode = MODE_BRIGHTNESS;
			float light = Float.parseFloat(nextModeValues[1]);
			setColor(R.color.white);
			setBright(light/100);
		}if(nextModeValues[0].equals("strobe")){
			//set screen strobe
			mCurrentMode = MODE_STROBE;
			setBright(1.0f);
			if(Long.parseLong(nextModeValues[1])>0){
				updateFlashUI(1000/((Long.parseLong(nextModeValues[1])+5)/10));
			}else{
				updateFlashUI(new Long(1000/5*10));
			}
		}if(nextModeValues[0].equals("customize")){
			mCurrentMode = MODE_CUSTOMIZE;
			setColor(R.color.white);
			//set screen customize
			Log.i("LedTorch", "next:customize");
			mCurrentMode = MODE_CUSTOMIZE;
			mFlag = 1;
			customizeDelayIndex = 1;
			customizeDelayValues = nextModeValues;
			if(customizeDelayValues.length>1){
				customizeLed(Long.parseLong(customizeDelayValues[customizeDelayIndex]));
			}
		}
	}
	private int calculateMode(int modeId){
		int nextModeId = 1;
		if(modeId<setting.getInt("screen_mode_count", screen_mode.getAll().size())){
			nextModeId = modeId + 1;
		}
		settingEditor.putInt("current_screen_mode", nextModeId);
		settingEditor.commit();
		return nextModeId;
	}
	private void setColor(int color_1) {
		myColor = getBaseContext().getResources();
		Drawable color_M = myColor.getDrawable(color_1);
		mylayout.setBackgroundDrawable(color_M);
	}
	private void setBright(float light) {
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.screenBrightness = light;
		getWindow().setAttributes(lp);
	}
	private PowerManager.WakeLock getWakeLock() {
		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG);
		return wl;
	}
	private void updateFlashUI(Long delay){
		if (mCurrentMode != MODE_STROBE) {
			return;
		}
		flashHandler = new FlashHandler();
		flashHandler.sleep(delay);
		if (mFlag == 1) {
			setColor(R.color.black);
			mFlag = 0;
		} else {
			setColor(R.color.white);
			mFlag = 1;
		}
	}
	class FlashHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle bundle =  msg.getData();
			ScreenTorch.this.updateFlashUI(bundle.getLong("delay"));
		}
		public void sleep(long delayMillis) {
			removeMessages(0);
			Message msg = new Message();
			Bundle data = new Bundle();
			data.putLong("delay", delayMillis);
			msg.setData(data);
			sendMessageDelayed(msg, delayMillis);
		}
	}
	private void customizeLed(long delay){
		if (mCurrentMode != MODE_CUSTOMIZE) {
			return;
		}
		if (mFlag == 1) {
			setColor(R.color.white);
			mFlag = 0;
		} else {
			setColor(R.color.black);
			mFlag = 1;
		}
		customizeHandler = new CustomizeHandler();
		customizeHandler.sleep(delay);
	}
	class CustomizeHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle bundle =  msg.getData();
			customizeLed(bundle.getLong("delay"));
		}
		public void sleep(long delayMillis) {
			removeMessages(0);
			customizeDelayIndex = customizeDelayIndex+1;
			if(customizeDelayIndex==customizeDelayValues.length)
				customizeDelayIndex=1;
			if(customizeDelayIndex<customizeDelayValues.length){
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putLong("delay", Long.parseLong(customizeDelayValues[customizeDelayIndex]));
				msg.setData(data);
				sendMessageDelayed(msg, delayMillis);
			}
		}
	}
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "Exit");
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			new ActivityUtil(this).exit();
			return true;
		}
		return false;
	}
}